import React,{useEffect,useState} from 'react'
import {useDispatch,useSelector} from "react-redux"
import * as action from "../../action"
import { ProductCard , Button} from 'react-vant';
import {useNavigate} from "react-router-dom"
import { SubmitBar, Checkbox } from 'react-vant';
function Shoparr() {
  let navigate = useNavigate()
  let [sumprice,setSumprice] = useState(0)
  let [sumnum ,setSumnum] = useState(0)
  let store = useSelector(state=>({...state.shopreducer}))
  let dispacth = useDispatch()
  let addfn = (id)=>{
      dispacth(action.addFn(id))
  }
  let delfn = (id)=>{
    dispacth(action.delFn(id))
  }
  let changeItem = (id)=>{
    dispacth(action.changeitem(id))
  }
  let changeALL = ()=>{
    dispacth(action.changeAll())
  }
  useEffect(()=>{
     let checkarr = store.shoparr.filter(item=>item.checked)
      let zongjia = checkarr.reduce((a,b)=>{
       return a + b.price * b.num
     },0)
     let sumnumber = checkarr.reduce((a,b)=>{
      return a +  b.num
    },0)
     setSumprice(zongjia)
     setSumnum(sumnumber)
  },[store.shoparr])
  return (
    <div>
      <input type="checkbox" checked={store.flagall} onChange={changeALL}/>
      {
        store.shoparr ?. map ((item,index)=>{
          return  <ProductCard
          key={index}
          num={item.num}
          price={item.price}
          desc={item.des}
          title={item.tit}
          thumb={item.img}
          footer={
            <>
              <input type="checkbox" checked={item.checked} onChange={()=>changeItem(item.id)}/>
              <Button size="mini" round plain style={{ marginRight: 2 }} onClick={()=>delfn(item.id)}>
                -
              </Button>
              <Button size="mini" round plain onClick={()=>addfn(item.id)}>
                +
              </Button>
            </>
          }
        />
        })
      }
      <div className="demo-submit-bar">
    <SubmitBar
      price={sumprice * 100 }
      buttonText="提交订单"
      tip={
        <>
          总个数为
          <span style={{ color: '#1989fa' }}>{sumnum}</span>
        </>
      }
    >
    </SubmitBar>
    </div>
    </div>
  )
}

export default Shoparr